package homework.day11;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 浏览器发送过来的请求内容每个字符单独读取出来并输出到控制台
 * @author XingHaiYang
 * @date 2022/9/17 10:54
 */
public class Test02 {
	private ServerSocket ss;

	public Test02() {
		try {
			System.out.println("服务器申请端口中...");
			ss = new ServerSocket(8088);
			System.out.println("申请成功！");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void start(){
		try {
			System.out.println("等待客户端连接...");
			Socket s = ss.accept();
			System.out.println("一个客户端连接成功！");
			Runnable r = new ClientHandler(s);
			Thread t = new Thread(r);
			t.start();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
		Test02 t2 = new Test02();
		t2.start();
	}
}
class Client{
	private Socket s;

	public static void main(String[] args) {
		Client c = new Client();
		c.start();
	}

	public Client() {
		try {
			System.out.println("连接服务器中...");
			s = new Socket("localhost",8088);
			System.out.println("连接服务器成功！");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void start(){
		try {
			OutputStream out = s.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
			Scanner scan = new Scanner(System.in);
			System.out.println("请输入：");
			while (true){
				String say = scan.nextLine();
				if("exit".equals(say)){
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
class ClientHandler implements Runnable{
	private Socket s;

	public ClientHandler(Socket s) {
		this.s = s;
	}
	@Override
	public void run() {
		try {
			InputStream in = s.getInputStream();
			InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
			int listen;
			while (true) {
				try {
					if ((listen=isr.read()) != -1){
						char c = (char)listen;
						System.out.println(c);
						break;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
